<template>
  <div class="right-tools">
    <!-- 上部：按钮 -->
    <div class="section button-section">
      <button @click="toggleSectionSelection" :disabled="!isSectionEnabled">
        断面
      </button>
      <button @click="toggleProfileSelection" :disabled="!isSectionEnabled">
        剖面
      </button>
      <button @click="dialogVisible = true">设置</button>
    </div>

    <div class="section chart-section" style="overflow-y: auto">
      <p>{{ layerDescription }}</p>
    </div>
    <div class="section download">
      <label for="element-select" style="color: rgba(255, 255, 255, 0.9)"
        >选择要素：</label
      >
      <el-select
        id="element-select"
        v-model="selectedElement"
        placeholder="请选择要素"
        style="
          background-color: rgba(40, 60, 80, 0.9);
          color: white;
          border: none;
          border-radius: 5px;
          padding: 5px;
          margin-right: 10px;
          width: 100%;
        "
      >
        <el-option
          v-for="item in elements"
          :key="item.value"
          :label="item.label"
          :value="item.value"
        />
      </el-select>

      <button
        @click="downloadData"
        style="
          background: linear-gradient(135deg, #00baff, #006de6);
          color: white;
          border: none;
          border-radius: 5px;
          cursor: pointer;
          padding: 10px 20px;
          font-size: 14px;
          transition: all 0.3s ease;
          box-shadow: 0 4px 15px rgba(0, 186, 255, 0.6);
          margin-top: 10px;
          width: 100%;
        "
      >
        下载
      </button>
      <button
        @click="clickopen"
        style="
          background: linear-gradient(135deg, #00baff, #006de6);
          color: white;
          border: none;
          border-radius: 5px;
          cursor: pointer;
          padding: 10px 20px;
          font-size: 14px;
          transition: all 0.3s ease;
          box-shadow: 0 4px 15px rgba(0, 186, 255, 0.6);
          margin-top: 10px;
          width: 100%;
        "
      >
        数据更新
      </button>
    </div>
    <div
      class="section chart-section-2"
      style="overflow-y: auto; overflow-x: hidden; overflow-wrap: break-word ;    margin-top: -50px;"
    >
      <p style="white-space: pre-wrap"><h4>数据日期说明：</h4>{{ layerDescription2 }}</p>
    </div>
    <div class="section control-section">
      <label
        for="depth-select"
        style="color: rgba(255, 255, 255, 0.9); margin-right: 10px"
        >深度</label
      >
      <el-select
        id="depth-select"
        v-model="selectedDepth"
        placeholder="请选择深度"
        style="
          width: 100px;
          background-color: rgba(28, 43, 54, 0.9);
          color: rgba(255, 255, 255, 0.9);
          border: none;
        "
        popper-class="custom-popper"
        :disabled="!isDepthSelectorEnabled"
      >
        <el-option
          v-for="item in options"
          :key="item.value"
          :label="item.label"
          :value="item.value"
        />
      </el-select>
    </div>
    <!-- 设置弹出框 -->
    <el-dialog title="Colorbar 设置" v-model="dialogVisible" width="40%">
      <el-form>
        <el-form-item label="选择图层">
          <el-select
            v-model="selectedLayerId"
            placeholder="请选择图层"
            @change="handleLayerChange"
          >
            <el-option
              v-for="item in layerOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>

        <el-form-item label="颜色梯度数量">
          <el-input-number
            v-model="gradientCount"
            :min="2"
            :max="20"
            @change="updateGradientColors"
          ></el-input-number>
          <el-button type="text" @click="resetColors" style="margin-left: 10px">
            重置默认
          </el-button>
        </el-form-item>

        <el-form-item
          v-for="(color, index) in gradientColors"
          :key="index"
          :label="'颜色 ' + (index + 1)"
        >
          <el-color-picker
            v-model="gradientColors[index]"
            show-alpha
          ></el-color-picker>
          <el-input
            v-model="gradientColors[index]"
            style="width: 100px; margin-left: 10px"
            placeholder="请输入颜色值"
          ></el-input>
          <el-button
            type="danger"
            icon="el-icon-delete"
            circle
            @click="removeColor(index)"
            style="margin-left: 10px"
            v-if="gradientColors.length > 2"
          ></el-button>
        </el-form-item>
      </el-form>

      <div class="colorbar-preview">
        <div
          class="colorbar-gradient"
          :style="{
            background: `linear-gradient(to right, ${gradientColors.join(
              ', '
            )})`,
          }"
        ></div>
      </div>

      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="saveColorbarSettings">保存</el-button>
      </span>
    </el-dialog>
    <Bottom :isExpanded="isExpanded" @update:isExpanded="updateIsExpanded" />
  </div>
</template>

<script setup>
import { computed, ref, watch, onMounted, onBeforeUnmount } from "vue";
import eventBus from "@/utils/eventBus";
import Bottom from "./Bottom.vue";
import { ElMessage } from "element-plus";
import { format } from "date-fns";

const props = defineProps({
  viewerHandle: {
    type: Object,
    required: true,
  },
});

const options = [
  { value: "1", label: "2米" },
  { value: "2", label: "5米" },
  { value: "3", label: "10米" },
  { value: "4", label: "30米" },
  { value: "5", label: "50米" },
  { value: "6", label: "70米" },
  { value: "7", label: "90米" },
  { value: "8", label: "110米" },
  { value: "9", label: "130米" },
  { value: "10", label: "150米" },
  { value: "11", label: "170米" },
  { value: "12", label: "190米" },
  { value: "13", label: "210米" },
  { value: "14", label: "230米" },
  { value: "15", label: "250米" },
  { value: "16", label: "270米" },
  { value: "17", label: "300米" },
  { value: "18", label: "350米" },
  { value: "19", label: "400米" },
  { value: "20", label: "450米" },
  { value: "21", label: "500米" },
  { value: "22", label: "550米" },
  { value: "23", label: "600米" },
  { value: "24", label: "650米" },
  { value: "25", label: "700米" },
  { value: "26", label: "750米" },
  { value: "27", label: "800米" },
  { value: "28", label: "850米" },
  { value: "29", label: "900米" },
  { value: "30", label: "950米" },
  { value: "31", label: "1000米" },
  { value: "32", label: "1100米" },
  { value: "33", label: "1200米" },
  { value: "34", label: "1300米" },
  { value: "35", label: "1400米" },
  { value: "36", label: "1500米" },
  { value: "37", label: "1600米" },
  { value: "38", label: "1700米" },
  { value: "39", label: "1800米" },
  { value: "40", label: "1900米" },
  { value: "41", label: "2000米" },];

const layerOptions = [
  { value: 19, label: "温度" },
  { value: 21, label: "盐度" },
  { value: 9, label: "海流强度" },
  { value: 23, label: "潮位" },
  { value: 13, label: "海表面高度" },
  { value: 15, label: "锋面强度" },
];

const layerDescription2 = computed(() => eventBus.getCurrentDescription2());
//  ref(`
// （1）中尺度涡、锋面、内波的时间覆盖范围：2023/01/01-2025/03/31，时间分辨率：每天。其中，内波反演受云量影响，建议选择每年的6-8月份
// （2）Argo跃层的时间覆盖范围：2023/01/01-2025/03/31，时间分辨率：每月
// （3）潜标01观测时间为2022.01.01-01.31
// （4）潜标02观测时间为2022.02.01-02.28
// `);

// 新增响应式变量
const currentLayer = ref("");
const isSectionEnabled = computed(() => {
  return currentLayer.value === 1 || currentLayer.value === 2;
});
const clickopen = () => {
  window.open('https://ecs.console.aliyun.com/vnc/index.htm?instanceId=i-bp1j70amn5xmxdggjwp1&regionId=cn-hangzhou&instanceName=launch-advisor-20250423');
}
// 监听eventBus中的当前图层变化
onMounted(() => {
  eventBus.$on("current-layer-change", (layer) => {
    currentLayer.value = layer;
  });
  eventBus.$on("section-dialog-closed", () => {
    isSelectingSection.value = false;
  });
  eventBus.$on("section-Profile-closed", () => {
    isSelectingProfile.value = false;
  });
  // 确保viewer实例已正确传递
  console.log("Received viewer instance:", props.viewerHandle);
});

onBeforeUnmount(() => {
  eventBus.$off("section-dialog-closed");
  eventBus.$off("current-layer-change");
});

const selectedLayerId = ref(null);
const isDepthSelectorEnabled = ref(false);
const enabledLayerIds = [1, 19, 20, 2, 21, 22, 3, 9, 10];
const isSelectingSection = ref(false);

function toggleSectionSelection() {
  // 每次点击都切换状态，无论之前是什么状态
  isSelectingSection.value = !isSelectingSection.value;
  let params = {
    isSelectingSection: isSelectingSection.value,
    type: currentLayer.value,
  };
  eventBus.$emit("toggle-section-selection", params);
}

// 更新深度选择器状态
const updateDepthSelectorState = (checkedKeys) => {
  isDepthSelectorEnabled.value = checkedKeys.some((key) =>
    enabledLayerIds.includes(key)
  );
  currentLayer.value = checkedKeys[0];
};

function handleLayerChange(layerId) {
  if (layerId) {
    gradientColors.value = [...eventBus.getLayerColors(layerId)];
    gradientCount.value = gradientColors.value.length;
  }
}

function resetColors() {
  if (selectedLayerId.value) {
    gradientColors.value = [
      ...eventBus.defaultLayerColors[selectedLayerId.value],
    ];
    gradientCount.value = gradientColors.value.length;
  }
}

function saveColorbarSettings() {
  if (selectedLayerId.value) {
    eventBus.updateLayerColors(selectedLayerId.value, [
      ...gradientColors.value,
    ]);
    dialogVisible.value = false;
  }
}

const elements = [
  { value: "1", label: "温度" },
  { value: "2", label: "盐度" },
  { value: "3", label: "海流" },
];

const layerDescription = computed(() => eventBus.getCurrentDescription());
const selectedElement = ref("");
const dialogVisible = ref(false);
const gradientCount = ref(5);
const gradientColors = ref([
  "#ff0000",
  "#ff7f00",
  "#ffff00",
  "#00ff00",
  "#0000ff",
]);
const selectedDepth = ref("2米");
const isExpanded = ref(false);

function toggleBottomPopup() {
  // 如果正在选择剖面，先取消选择
  if (isSelectingProfile.value) {
    isSelectingProfile.value = false;
    eventBus.$emit("toggle-profile-selection", { isSelectingProfile: false });
  }
  isExpanded.value = !isExpanded.value;
}

function updateIsExpanded(value) {
  isExpanded.value = value;
}

function updateGradientColors(newVal) {
  if (newVal > gradientColors.value.length) {
    for (let i = gradientColors.value.length; i < newVal; i++) {
      gradientColors.value.push("#000000");
    }
  } else {
    gradientColors.value = gradientColors.value.slice(0, newVal);
  }
}

async function downloadData() {
  if (!selectedElement.value) {
    ElMessage.warning("请先选择要下载的要素");
    return;
  }

  const currentTime =
    format(eventBus.selectedDate, "yyyy-MM-dd' 'HH:mm:ss", {
      timeZone: "UTC",
    }) || "2025-03-19";

  const params = {
    ctime: currentTime,
    type: parseInt(selectedElement.value),
  };

  const url = `/api/public/dow?ctime=${params.ctime}&type=${params.type}`;
  window.open(url, "_blank");
}
const isSelectingProfile = ref(false);

function toggleProfileSelection() {
  isSelectingProfile.value = !isSelectingProfile.value;
  let params = {
    isSelectingProfile: isSelectingProfile.value,
    type: currentLayer.value,
  };
  eventBus.$emit("toggle-profile-selection", params);
}
// 监听eventBus中的图层变化
onMounted(() => {
  eventBus.$on("layer-check-change", updateDepthSelectorState);
});

onBeforeUnmount(() => {
  eventBus.$off("layer-check-change");
});

watch(gradientCount, (newVal) => {
  updateGradientColors(newVal);
});
watch(selectedDepth, (newDepth) => {
  const depthNumber = parseInt(newDepth.replace("第", "").replace("层", ""));
  eventBus.setCurrentDepth(depthNumber); // 触发深度变化事件
});
</script>

<style scoped>
.right-tools {
  width: 15%;
  height: 93%;
  position: fixed;
  top: 0px;
  z-index: 999;
  background-color: rgba(24, 44, 70, 0.8);
  right: 0;
  border-radius: 10px 0 0 10px;
  display: flex;
  flex-direction: column;
  padding: 10px;
}

.section {
  display: flex;
  justify-content: center;
  align-items: center;
  position: relative;
}

.button-section {
  display: flex;
  flex-direction: row;
  gap: 10px;
  padding: 5px;
}

.button-section button:disabled {
  opacity: 0.5;
  cursor: not-allowed;
  background: linear-gradient(135deg, #666, #333);
  box-shadow: none;
}

.button-section button:disabled:hover {
  transform: none;
  box-shadow: none;
}

.button-section button {
  background: linear-gradient(135deg, #00baff, #006de6);
  color: white;
  border: none;
  border-radius: 5px;
  cursor: pointer;
  padding: 10px 20px;
  font-size: 14px;
  transition: all 0.3s ease;
  box-shadow: 0 4px 15px rgba(0, 186, 255, 0.6);
}

.button-section button:hover {
  transform: translateY(-2px);
  box-shadow: 0 8px 25px rgba(0, 186, 255, 0.8);
}

.chart-section {
  width: 100%;
  height: 310px;
  display: flex;
  justify-content: center;
  align-items: center;
  background-color: rgba(28, 43, 54, 0.8);
  border-radius: 5px;
  padding: 20px;
  margin-bottom: 10px;
}

.chart-section-2 {
  width: 100%;
  height: 220px;
  display: flex;
  justify-content: center;
  align-items: center;
  background-color: rgba(28, 43, 54, 0.8);
  border-radius: 5px;
  padding: 20px;
  margin-bottom: 10px;
}

.chart-section-2 p {
  width: 100%;
  overflow-wrap: break-word;
  height: 180px;
  margin-right: 25px;
  color: rgba(255, 255, 255, 0.9);
  font-size: 16px;
  line-height: 1.6;
}

.chart-section p {
  height: 220px;
  margin-right: 25px;
  color: rgba(255, 255, 255, 0.9);
  font-size: 16px;
  line-height: 1.6;
  text-align: center;
}

.download {
  height: 280px;
  margin-top: 10px;
  display: flex;
  flex-direction: column;
  align-items: flex-start;
  gap: 10px;
  padding: 10px;
  background-color: rgba(28, 43, 54, 0.8);
  border-radius: 5px;
  width: 90%;
}

.control-section {
  margin-top: 20px;
  display: flex;
  align-items: center;
}

/* 其他样式保持不变... */
</style>
